package com.wisdytech.linkdcs.equipLifeCycle.malfunction.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.enums.MalfunctionComfirmEnum;
import com.wisdytech.common.enums.MalfunctionStatusEnum;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenanceDetailDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenancePlanDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenanceRecordDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenanceTaskDao;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.dao.IMProcessRecordDao;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.model.MProcessRecord;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.model.MalfunctionRecord;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.model.TPReplaceTemp;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.service.IMProcessRecordService;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.service.ITPReplaceTempService;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.vo.MProcessVo;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.service.IEquipmentRegisteredService;
import com.wisdytech.linkdcs.partLife.dto.PartReplaceDTO;
import com.wisdytech.linkdcs.partLife.model.KeyPart;
import com.wisdytech.linkdcs.partLife.model.ModelPart;
import com.wisdytech.linkdcs.partLife.model.Part;
import com.wisdytech.linkdcs.partLife.service.IKeyPartService;
import com.wisdytech.linkdcs.partLife.service.IModelPartService;
import com.wisdytech.linkdcs.partLife.service.IPartReplaceService;
import com.wisdytech.linkdcs.partLife.service.IPartService;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.model.EqToolConfig;
import com.wisdytech.linkdcs.tool.service.IEqToolConfigService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dailibo
 * @since 2018-06-11
 */
@Service
@Transactional
public class MProcessRecordServiceImpl extends BaseService<IMProcessRecordDao, MProcessRecord> implements IMProcessRecordService {

	private Logger logger =LoggerFactory.getLogger(getClass());
	
	@Autowired
	private IMProcessRecordDao iMProcessRecordDao;
	
	@Resource
	private ITPReplaceTempService iTPReplaceTempService;
	
	@Resource
	private IMaintenanceRecordDao iMaintenanceRecordDao;
	@Resource
	private IMaintenanceDetailDao iMaintenanceDetailDao;
	@Resource
	private IMaintenanceTaskDao iMaintenanceTaskDao;
	@Resource
	private IMaintenancePlanDao iMaintenancePlanDao;
	@Resource
	private IPartReplaceService iPartReplaceService;
	@Resource
	private IEquipmentRegisteredService equipmentRegisterService;
	@Resource
	private IPartService iPartService;
	@Resource
	private IKeyPartService iKeyPartService;
	@Resource
	private IModelPartService iModelPartService;
	@Resource
	private IEqToolConfigService iEqToolConfigService;
	
	@Autowired
	private IEqEquipmentDao iEqEquipmentDao;
	
	@Override
	public boolean processRecord(MProcessRecord pReocrd,String username) {
		//更新记录表
		String recordId =pReocrd.getRecordId();
		MalfunctionRecord record=new MalfunctionRecord();
		record.setPkId(recordId);
		record.setUpdateUser(username);
		record.setUpdateDate(new Date());
		
		if(MalfunctionComfirmEnum.no.getCode().equals(pReocrd.getComfirmFlag())){
			//不需要确认
			record.setFailureResult("1");
			record.setFailureStatus(MalfunctionStatusEnum.ok.getCode());
		}else {
			//待确认
			record.setFailureStatus(MalfunctionStatusEnum.confirm.getCode());
		}
		//更新不成功
		if(!record.updateById()) {
			throw new ServiceException("故障处理更新记录失败");
		}
		
		//插入处理记录
		pReocrd.setPkId(BaseUtil.getUUID());
		
		
		//同步更新备件及工装更换
		Filter filter = new Filter();
		filter.setSize(65533);
		PageInfo<TPReplaceTemp> temps =this.iTPReplaceTempService.getTemps(filter, recordId);
		List<TPReplaceTemp> templist = temps.getList();
		for(TPReplaceTemp tPReplaceTemp :templist) {
			tPReplaceTemp.setRecordId(pReocrd.getPkId());
			tPReplaceTemp.setFlag("1");
			this.iTPReplaceTempService.update(tPReplaceTemp);
		}
		//获取设备编码
		MalfunctionRecord mRecord =record.selectById(recordId);
		Equipment  equipment =
				iEqEquipmentDao.selectByEquipCode(mRecord.getEquipCode());
		
		//同步更换信息
        if(!templist.isEmpty()){
            this.savePartReplace(templist,equipment.getPkId());
        }

		return pReocrd.insert();
	}

	@Override
	public MProcessVo getProcessRecord(String recordId) {
		
		MProcessVo mProcessVo =
				iMProcessRecordDao.selectProcessDetail(recordId);
		return mProcessVo;
	}
	
	
	private void savePartReplace(List<TPReplaceTemp> templist,String equipId) {
		for(TPReplaceTemp tPReplaceTemp : templist) {
			//更换备件
			if(tPReplaceTemp.getType().equals("0")) {
				this.savePartRep(equipId, tPReplaceTemp);
			}
			//更换工装
			if(tPReplaceTemp.getType().equals("1")) {
				this.saveToolRep(equipId,tPReplaceTemp);
			}
		}
	}
	//同步工装的更换
	private void saveToolRep(String equipId, TPReplaceTemp tPReplaceTemp) {
		SysUser user = BaseUtil.getCurrentUser();
		EqToolConfig eqToolConfig = new EqToolConfig();
		if(tPReplaceTemp.getUseFlag().equals("0")) {
			eqToolConfig.setRepair("1");
		}
		if(tPReplaceTemp.getUseFlag().equals("1")) {
			eqToolConfig.setScrap("1");
		}
		eqToolConfig.setToolCode(tPReplaceTemp.getCode());//新编码
		eqToolConfig.setOriginToolCode(tPReplaceTemp.getoCode());//原编码
		eqToolConfig.setReplaceDate(new Date());
		eqToolConfig.setReplaceReason("故障");
		eqToolConfig.setReplaceUser(user.getUsername());
		this.iEqToolConfigService.replaceToolTemp(eqToolConfig, user,equipId);
		
	}
	//同步备件更换
	private void savePartRep(String equipId,TPReplaceTemp tPReplaceTemp) {
		PartReplaceDTO partReplacedto = new PartReplaceDTO();
		partReplacedto.setEquipId(equipId);
		//获取备件型号信息
		Part part =iPartService.getPartByPartCode(tPReplaceTemp.getCode());
		ModelPart modelPart = iModelPartService.getModelPartIdByPkIdAndEqId(tPReplaceTemp.getLocationCode());
		partReplacedto.setPartId(modelPart.getPkId());
		if(part.getKeyPartFlag()!=null) {
			partReplacedto.setKeyPartFlag(part.getKeyPartFlag().toString());
		}
		//通过
		if(tPReplaceTemp.getoSerialNum()!=null && tPReplaceTemp.getoSerialNum()!="") {
			KeyPart keyParto = iKeyPartService.getKeyPartByOseri(tPReplaceTemp.getoSerialNum());
			partReplacedto.setoSerialNum(keyParto.getPkId());
		}
		if(tPReplaceTemp.getnSerialNum()!=null && tPReplaceTemp.getnSerialNum()!="") {
			KeyPart keyPartn = iKeyPartService.getKeyPartByOseri(tPReplaceTemp.getnSerialNum());
			partReplacedto.setnSerialNum(keyPartn.getPkId());
		}
	    SysUser userSession = BaseUtil.getCurrentUser();
	    String userId = userSession.getPkId();
	    partReplacedto.setRepUser(userId);
	    partReplacedto.setRepReason("故障");
	    partReplacedto.setRepNum(tPReplaceTemp.getNum());
	    if(tPReplaceTemp.getUseFlag() != null && tPReplaceTemp.getUseFlag()!="") {
	    	partReplacedto.setStatus(Double.parseDouble(tPReplaceTemp.getUseFlag()));
	    }
	    iPartReplaceService.savePartReplaceTemp(partReplacedto);
	}
	

}
